package br.com.intelsys.basics.spring;

import java.util.GregorianCalendar;

import br.com.intelsys.basics.spring.CookieMap;
import br.com.intelsys.basics.utils.DateOpers;
import br.com.intelsys.basics.utils.DateOpers.Field;
import br.com.intelsys.security.itoken.IToken;
import br.com.intelsys.security.itoken.ITokenException;
import br.com.intelsys.security.itoken.ITokenNotFoundException;
import br.com.intelsys.security.itoken.ITokenService;

public abstract class CookieServiceAbstract {
	private final ITokenService iTokenService;
	public static final String KEEP_LOGGED = "KL";

	public CookieServiceAbstract(ITokenService iTokenService) {
		this.iTokenService = iTokenService;
	}

	public IToken checkKeepLogged(boolean isLogged, CookieMap cookieMap) {
		if (isLogged) {
			return null;
		}
		if (cookieMap.containsKey(KEEP_LOGGED)) {
			try {
				return iTokenService.useToken(cookieMap.get(KEEP_LOGGED).getValue());
			} catch (ITokenException e) {
				cookieMap.remove(KEEP_LOGGED);
			}
		}
		return null;
	}

	public void saveKeepLogged(CookieMap cookieMap, IToken iToken) {
		cookieMap.put(KEEP_LOGGED, iToken.getEncodedToken(),
				DateOpers.getDifference(new GregorianCalendar().getTime(), iToken.getDateExpires(), Field.SECOND));
	}

	public void removeKeepLogged(CookieMap cookieMap) {
		if (cookieMap.containsKey(KEEP_LOGGED)) {
			try {
				iTokenService.revokeEncodedToken(cookieMap.get(KEEP_LOGGED).getValue());
			} catch (ITokenNotFoundException e) {
			}
			cookieMap.remove(KEEP_LOGGED);
		}
	}
}
